import * as Koa from 'koa';
import { Transaction } from 'tiny-entity2';
import { Guid, route, RouteOptionsVerify, ServiceManager, UsingLock } from "../../common";
import { ServiceException } from '../../common/excpetion';
import { ApiDataContext } from '../../domain/apiDataContext';
import { OrganizationTree } from '../../domain/models/organizationTree';
import { OrganizationTreeService } from '../../service/OrganizationTreeService';
const orzTreeSvr = ServiceManager.Current.GetService<OrganizationTreeService>('OrganizationTreeService');

class OrganizationTreeController {
    @route(new RouteOptionsVerify('GET', '/api/organizationTree'))
    async queryOrganizationTrees(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let params = ctx.query;
        if (!rootOrgId) rootOrgId = "";
        params.organizationId = rootOrgId;

        let data = await orzTreeSvr.QueryOrganizationTree(params);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('GET', '/api/organizationTree/:id'))
    async getOrganizationTreeInfoById(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let id = ctx.params.id;
        let data = await orzTreeSvr.GetOrganizationTreeById(id);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('PUT', '/api/organizationTree'))
    async updateorganizationTree(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let orgtrees: OrganizationTree[] = ctx.request.body;
        let resultNodes: OrganizationTree[] = [];
        let nodeidobj=orgtrees.find(x=>x.id==null ||x.id==undefined || x.id=="");
        if(nodeidobj)
        {
            throw new ServiceException('节点Id不能为空');
        }
        ctx.response.body = await UsingLock(rootOrgId, async () => {
            return await Transaction(new ApiDataContext(), async datactx => {
                orgtrees.forEach(async x=> {
                    let currTreeNode = await orzTreeSvr.GetOrganizationTreeById(x.id);
                    currTreeNode.parentId=x.parentId;
                    let result = await orzTreeSvr.UpdateorganizationTree(currTreeNode, datactx);
                    resultNodes.push(result);
                    return resultNodes;
                });
            });
        })

        await next();
    }
}